﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Xml;
using System.Text;
using System.Web.UI;

namespace JCTimes.Portal.Infrastructure
{

    public enum FileType
    {
        Pic,
        Rar,
        Excel,
        Cert,
        EntryOrder_Invoice,
        EntryOrder_Container,
        EntryOrder_Contract,
        EntryOrder_Other,
        LadingContainerBill,
        OrderContainerPkg,
        Vedio,
        Photo
    }

    public enum FilePathDir
    {
        Carrier,
        SeaExpress,
        Cert,
        ContainerFeeQueryOrder,//拖车费询价
        FormatBill,
        OrderContainerPkg,
        EntryOrder,
        LadingContainerBill,
        Vedio,
        Photo,
        PackingList
    }


    public static class FilesManager
    {

        /// <summary>
        /// 获取上传文件 by Yao Qi
        /// </summary>
        /// <param name="uploadFile">上传文件</param>
        /// <param name="fileType">文件类型</param>
        /// <param name="fileName">输出文件名</param>
        /// <param name="errMsg">错误信息</param>
        /// <returns></returns>
        public static bool GetUploadFile(HttpPostedFileBase uploadFile, FileType fileType, FilePathDir dir, out string fileName, out string errMsg)
        {
            string filePath = "";
            errMsg = "";
            fileName = "";
            if (uploadFile == null)
            {
                errMsg = "请选择文件！";
                return false;
            }
            string fileDir = HttpContext.Current.Server.MapPath(GetFilePathDir(dir));
            FileInfo fi = new FileInfo(uploadFile.FileName);
            fileName = fi.Name;
            List<string> list = GetFileExtensions(fileType);
            if (list == null || list.Count == 0)
            {
                errMsg = "文件类型不正确";
                return false;
            }
            if (!list.Contains(fi.Extension))
            {
                errMsg = "文件类型不正确";
                return false;
            }


            XmlTextReader reader = new XmlTextReader(System.Web.HttpContext.Current.Server.MapPath("~/Resource/FileTypes.xml")); // new一个XMLTextReader实例
            XmlDocument doc = new XmlDocument();
            doc.Load(reader);

            //关闭reader，不然config文件就变成只读的了
            reader.Close();
            //文件大小
            string fileLength = "";

            //读取XML对应节点
            XmlNode xn = doc.SelectSingleNode("/Root/FileProperty/FileLength");
            fileLength = xn.Attributes["Length"].Value;

            int tempSize = 3;
            int.TryParse(fileLength, out tempSize);
            int size = tempSize * 1024 * 1024;
            if (uploadFile.ContentLength > size)
            {
                errMsg = "文件太大";
                return false;
            }

            filePath = Path.Combine(fileDir, fileName);
            try
            {
                if (!Directory.Exists(fileDir)) {
                    Directory.CreateDirectory(fileDir);
                }
                if (File.Exists(filePath))
                {
                    fileName = fileName.ToTimestamped();
                    filePath = Path.Combine(fileDir, fileName);
                }
                uploadFile.SaveAs(filePath);
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex.Message, ex);
                errMsg = ex.Message;
                return false;
            }

            return true;

        }

        /// <summary>
        /// 获取文件后缀 by Yaoqi
        /// </summary>
        /// <param name="fileType"></param>
        /// <returns></returns>
        public static List<string> GetFileExtensions(FileType fileType)
        {

            XmlTextReader reader = new XmlTextReader(System.Web.HttpContext.Current.Server.MapPath("~/Resource/FileTypes.xml")); // new一个XMLTextReader实例
            XmlDocument doc = new XmlDocument();
            doc.Load(reader);

            //关闭reader，不然config文件就变成只读的了
            reader.Close();

            List<string> list = new List<string>();

            //读取XML对应节点
            XmlNodeList xnList = doc.SelectSingleNode("/Root/FileType/" + fileType).ChildNodes;
            foreach (XmlNode node in xnList)
            {
                string s = node.Attributes["ID"].Value;
                list.Add(s);
            }
            return list;
        }

        /// <summary>
        /// 获取上传文件路径 by YaoQi
        /// </summary>
        /// <param name="dir"></param>
        /// <returns></returns>
        public static string GetFilePathDir(FilePathDir dir)
        {
            XmlTextReader reader = new XmlTextReader(System.Web.HttpContext.Current.Server.MapPath("~/Resource/FileTypes.xml")); // new一个XMLTextReader实例
            XmlDocument doc = new XmlDocument();
            doc.Load(reader);

            //关闭reader，不然config文件就变成只读的了
            reader.Close();
            string filepath = "";

            //读取XML对应节点
            XmlNode xn = doc.SelectSingleNode("/Root/DirPath/" + dir);
            filepath = xn.Attributes["Path"].Value;
            return filepath;
        }

        /// <summary>
        /// 获取下载文件的路径
        /// </summary>
        /// <param name="dir"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static string GetDownLoad(FilePathDir dir, string fileName)
        {
            return Path.Combine(GetFilePathDir(dir), fileName);
        }

        /// <summary>
        /// 导出txt文档
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="content"></param>
        public static void ExportTxtFile(Page page,string filename, string content)
        {
            //System.Web.HttpContext.Current.Response.Clear();
            //System.Web.HttpContext.Current.Response.Buffer = false;
            //System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream";
            //System.Web.HttpContext.Current.Response.AppendHeader("content-disposition", "attachment;filename=" + filename + ".txt;");
            //System.Web.HttpContext.Current.Response.Write(content);
            //System.Web.HttpContext.Current.Response.Flush();
            //System.Web.HttpContext.Current.Response.End();

            System.Web.HttpContext.Current.Response.Clear();
            System.Web.HttpContext.Current.Response.Buffer = true;
            System.Web.HttpContext.Current.Response.Charset = "UTF-8";
            System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + filename + ".txt");
            System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");//设置输出流为简体中文 
            System.Web.HttpContext.Current.Response.ContentType = "text/plain";//设置输出文件类型为txt文件。  
            System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN", true);
            System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad);
            System.Web.HttpContext.Current.Response.Write(content);
            System.Web.HttpContext.Current.Response.End(); 
        }
    }
}